#include "global.h"
#include "ArchHooks_Wii.h"
#include "RageLog.h"
#include "RageDisplay_GX.h"

#include <sys/time.h>
#include <ctime>
#include <wiiuse/wpad.h>
#include <ogc/pad.h>
#include <aesndlib.h>
#include <gccore.h>
#include <ogcsys.h>
#include <unistd.h>
#include <errno.h>
#include <fat.h>
#include <ogc/lwp_watchdog.h>

#include <debug.h>

void Wii_Reset() {
	SYS_ResetSystem(SYS_RETURNTOMENU, 0, 0);
}

void Wii_Power() {
	SYS_ResetSystem(SYS_POWEROFF_STANDBY, 0, 0);
}

void Wiimote_Power(s32 chan) {
	if(chan == 0)
		SYS_ResetSystem(SYS_POWEROFF_STANDBY, 0, 0);
}

ArchHooks_Wii::ArchHooks_Wii() {
	printf("Initializing Wii Hardware");
	
	printf("Video...");
	//VIDEO_Init();
	printf("Wiimotes...");
	WPAD_Init();
	printf("Gamepads...");
	PAD_Init();
	
	printf("Initializing system callbacks");
	SYS_SetPowerCallback(Wii_Power);
	SYS_SetResetCallback(Wii_Reset);
	WPAD_SetPowerButtonCallback(Wiimote_Power);
	
	printf("Initializing filesystem...\n");
	if(fatInitDefault()) {
		if(!chdir("sd:/")) {
			char buf[PATH_MAX];
			printf("Filesystem initialized (%s)\n", getcwd(buf, PATH_MAX));
			return;
		} else {
			printf("Couldn't chdir: %s", strerror(errno));
		}
	} else {
		printf("Couldn't initialize libFAT");
	}
	printf("Filesystem failed to initialize... press HOME to quit...");
	while(1) {
		WPAD_ScanPads();
		if(WPAD_ButtonsDown(0) & WPAD_BUTTON_HOME)
			exit(0);
	}
}

int64_t ArchHooks::GetMicrosecondsSinceStart(bool accurate) {
	static int64_t start = gettime();
	int64_t ret = diff_usec(start, gettime());
	if( accurate )
		ret = FixupTimeIfBackwards( ret );
	return ret;
}